package com.carnation.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import com.carnation.bean.GroupMenu;
import com.carnation.bean.HeadMenu;
import com.carnation.bean.Menu;
import com.carnation.bean.User;
import com.carnation.service.FileService;
import com.carnation.service.impl.FileServiceImpl;

public class MenuWrite {
	
	MenuFileUtril menuFileUtril = new MenuFileUtril();
	private ReentrantLock lock = new ReentrantLock();
	private FileService fileMgr = new FileServiceImpl();
	private Logger logger = Logger.getLogger(MenuWrite.class);
	
	public boolean writeHead(HeadMenu headMenu){
		if(headMenu == null){
			return false;
		}
		String fileName = menuFileUtril.getFileNameWithPath();
		File file = new File(fileName);
		if(!file.exists()){
			logger.error("菜单文件不存在");
			return false;
		}
		lock.tryLock();
		try{
			SAXReader reader = new SAXReader();
			Document document = reader.read(file);
			Element root = document.getRootElement();
			Element head = root.addElement("head");
			head.addAttribute("id", headMenu.getId());
			head.addAttribute("name", headMenu.getName());
			head.addAttribute("title", headMenu.getTitle());
			head.addAttribute("text", headMenu.getText());
			head.addAttribute("icon", headMenu.getIcon());
			OutputFormat format = OutputFormat.createPrettyPrint();
			format.setEncoding("UTF-8");
			XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
			writer.write(document);
			writer.close();
			return true;
		}
		catch(Exception e){
			logger.error("创建新的头部主菜单失败",e);
			return false;
		}
		finally{
			lock.unlock();
		}
	}
	
	@SuppressWarnings("rawtypes")
	public boolean writeGroupMenu(String parentId,GroupMenu groupMenu){
		if(groupMenu == null){
			logger.info("组菜单为空");
			return false;
		}
		else{
			String fileName = menuFileUtril.getFileNameWithPath();
			File file = new File(fileName);
			if(!file.exists()){
				logger.error("菜单文件不存在");
				return false;
			}
			lock.lock();
			try{
				SAXReader saxReader = new SAXReader();
				Document document = saxReader.read(file);
				Iterator headMenuList = document.selectNodes("/root/head").iterator();
				Element target = null;
				while(headMenuList.hasNext()){
					Element e = (Element)headMenuList.next();
					if(parentId.equals(e.attributeValue("id"))){
						target = e;
						break;
					}
				}
				if(target == null){
					logger.error("找不到组菜单所属的头部菜单");
					return false;
				}
				Element group = target.addElement("group");
				group.addAttribute("id", groupMenu.getId());
				group.addAttribute("name", groupMenu.getName());
				group.addAttribute("icon", groupMenu.getIcon());
				OutputFormat format = OutputFormat.createCompactFormat();
				format.setEncoding("UTF-8");
				XMLWriter writer = new XMLWriter(new FileOutputStream(file),format);
				writer.write(document);
				writer.close();
				return true;
			}
			catch(Exception e){
				logger.error("写组菜单失败",e);
				return false;
			}
			finally{
				lock.unlock();
			}
		}
	}
	
	@SuppressWarnings("rawtypes")
	public boolean writeMenu(String parentId,Menu menu,User user){
		if(menu == null ){
			logger.error("菜单为空");
			return false;
		}
		else{
			String fileName = menuFileUtril.getFileNameWithPath();
			File file = new File(fileName);
			if(!file.exists()){
				logger.error("菜单文件不存在");
				return false;
			}
			lock.tryLock();
			try {
				SAXReader reader = new SAXReader();
				Document document = reader.read(file);
				Iterator groupMenu = document.selectNodes("/root/head/group").iterator();
				Element target = null;
				while(groupMenu.hasNext()){
					Element e = (Element)groupMenu.next();
					if(parentId.equals(e.attributeValue("id"))){
						target = e;
						break;
					}
				}
				if(target == null){
					logger.info("没有找到对应的group");
					return false;
				}
				Element menueElement = target.addElement("menu");
				menueElement.addAttribute("id", menu.getId());
				menueElement.addAttribute("name", menu.getName());
				menueElement.addAttribute("icon", menu.getIcon());
				menueElement.addAttribute("url", menu.getUrl());
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setEncoding("UTF-8");
				XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
				writer.write(document);
				writer.close();
				fileMgr.createDirectory(menu,user);
				return true;
			} catch (Exception e) {
				logger.error("写菜单出错",e);
				return false;
			}
			finally{
				lock.unlock();
			}
		}
	}

	public boolean modifyHead(HeadMenu headMenu){
		if(headMenu == null){
			logger.error("传入的头部菜单为空");
			return false;
		}
		lock.tryLock();
		try{
			File file = checkFileExists(menuFileUtril.getFileNameWithPath());
			if(file == null){
				logger.error("没有找到菜单文件");
				return false;
			}
			else{
				SAXReader reader = new SAXReader();
				reader.setEncoding("UTF-8");
				Document document = reader.read(file);
				Element target = (Element)document.selectSingleNode("/root/head[@id='"+ headMenu.getId()+ "']");
				if(target == null){
					logger.error("找不到需要修改的头部菜单");
					return false;
				}
				else{
					@SuppressWarnings("rawtypes")
					List attributes = target.attributes();
					for(int i =0;i<attributes.size();i++){
						Attribute a = (Attribute)attributes.get(i);
						if(a.getName().equals("name")){
							a.setValue(headMenu.getName());
						}
						else if(a.getName().equals("title")){
							a.setValue(headMenu.getTitle());
						}
						else if(a.getName().equals("icon")){
							a.setValue(headMenu.getIcon());
						}
					}
					target.setAttributes(attributes);
					OutputFormat outputFormat = OutputFormat.createPrettyPrint();
					outputFormat.setEncoding("UTF-8");
					XMLWriter writer = new XMLWriter(new FileOutputStream(file), outputFormat);
					writer.write(document);
					writer.close();
					return true;
				}
			}
		}
		catch(Exception e){
			logger.error("修改头部菜单出错",e);
			return false;
		}
		finally{
			lock.unlock();
		}
	}

	public boolean modifyGroup(GroupMenu groupMenu){
		if(groupMenu == null){
			logger.error("传入的组菜单为空");
			return false;
		}
		lock.tryLock();
		try {
			File file = checkFileExists(menuFileUtril.getFileNameWithPath());
			if(file == null){
				logger.error("找不到菜单文件");
				return false;
			}
			else{
				SAXReader reader = new SAXReader();
				reader.setEncoding("UTF-8");
				Document document = reader.read(file);
				Element targert = (Element)document.selectSingleNode("/root/head/group[@id='" + groupMenu.getId() +"']");
				if(targert == null){
					logger.error("找不到对应的组菜单");
					return false;
				}
				else{
					@SuppressWarnings("rawtypes")
					List attributes = targert.attributes();
					for(int i=0 ;i<attributes.size();i++){
						Attribute a = (Attribute)attributes.get(i);
						if(a.getName().equals("name")){
							a.setValue(groupMenu.getName());
						}
						else if(a.getName().equals("icon")){
							a.setValue(groupMenu.getIcon());
						}
					}
					targert.setAttributes(attributes);
					OutputFormat format = OutputFormat.createPrettyPrint();
					format.setEncoding("UTF-8");
					XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
					writer.write(document);
					writer.close();
					return true;
				}
			}
		} catch (Exception e) {
			logger.error("修改组菜单失败",e);
			return false;
		}
		finally{
			lock.unlock();
		}
	}

	public boolean modfiyMenu(Menu menu){
		if(menu == null){
			logger.info("传入的menu为空");
			return false;
		}
		else{
			lock.tryLock();
			try{
				File file = checkFileExists(menuFileUtril.getFileNameWithPath());
				if(file == null){
					logger.error("菜单文件不存在");
					return false;
				}
				else{
					SAXReader reader = new SAXReader();
					reader.setEncoding("UTF-8");
					Document document = reader.read(file);
					Element target = (Element)document.selectSingleNode("/root/head/group/menu[@id='" + menu.getId() + "']");
					if(target == null){
						logger.error("找不到对应的菜单");
						return false;
					}
					else{
						@SuppressWarnings("rawtypes")
						List attributs = target.attributes();
						for(int i=0;i<attributs.size(); i++){
							Attribute a = (Attribute)attributs.get(i);
							if(a.getName().equals("name")){
								a.setValue(menu.getName());
							}
							else if(a.getName().equals("icon")){
								a.setValue(menu.getIcon());
							}
						}
						target.setAttributes(attributs);
						OutputFormat format = OutputFormat.createPrettyPrint();
						format.setEncoding("UTF-8");
						XMLWriter writer = new XMLWriter(new FileOutputStream(file), format);
						writer.write(document);
						writer.close();
						return true;
					}
				}
			}
			catch(Exception e){
				logger.error("修改菜单失败",e);
				return false;
			}
			finally{
				lock.unlock();
			}
		}
	}
	
	private File checkFileExists(String path){
		File file = new File(path);
		if(!file.exists()){
			logger.error("菜单文件不存在");
			return null;
		}
		return file;
	}
}
